/*
 * Copyright 2011 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gaellalire.jzip.model.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.gaellalire.jzip.model.InZipFile;

/**
 *
 * @author Gael Lalire
 */
public final class InZipFileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(InZipFileUtils.class);

    private InZipFileUtils() {
    }

    public static File copyTo(final ZipFile zipFile, final InZipFile inZipFile, final File directory, final CreationListener creationListener) throws IOException {
        File file = new File(directory, inZipFile.getName());
        if (inZipFile.isDirectory()) {
            file.mkdirs();
            if (!file.exists()) {
                throw new IOException("Unable to create dirs");
            }
            for (InZipFile subInZipFile : inZipFile.getChildren()) {
                copyTo(zipFile, subInZipFile, file, creationListener);
            }
        } else {
            if (!file.exists()) {
                ZipArchiveEntry zipEntry = inZipFile.getZipEntry();
                long externalAttributes = zipEntry.getExternalAttributes();
                long pStat = externalAttributes >> 16;
                long fileType = pStat >> 9;

                if (fileType == 0120) {
                    InputStream inputStream = zipFile.getInputStream(zipEntry);
                    try {
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        IOUtils.copy(inputStream, output);
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(output
                                .toByteArray())));
                        String readLine = bufferedReader.readLine();
                        Runtime.getRuntime().exec(new String[] {"ln", "-s", readLine, file.getAbsolutePath()});
                    } finally {
                        inputStream.close();
                    }
                } else {
                    boolean canRead = (pStat & 4) != 0;
                    boolean canReadUserOnly = (pStat & (256 + 32)) == 0;
                    boolean canWrite = (pStat & 2) != 0;
                    boolean canWriteUserOnly = (pStat & (128 + 16)) == 0;
                    boolean canExecute = (pStat & 4) != 0;
                    boolean canExecuteUserOnly = (pStat & (64 + 8)) == 0;

                    FileOutputStream output = new FileOutputStream(file);
                    try {

                        InputStream inputStream = zipFile.getInputStream(zipEntry);
                        try {
                            IOUtils.copy(inputStream, output);
                        } finally {
                            inputStream.close();
                        }
                        file.setReadable(canRead, canReadUserOnly);
                        file.setWritable(canWrite, canWriteUserOnly);
                        file.setExecutable(canExecute, canExecuteUserOnly);
                    } finally {
                        output.close();
                    }
                }
                creationListener.create(file, inZipFile);
                file.deleteOnExit();
            }
        }
        return file;
    }

    @SuppressWarnings("unchecked")
    public static List<InZipFile> create(final ZipFile zipFile) throws IOException {
        List<InZipFile> inZipFiles = new ArrayList<InZipFile>();
        for (ZipArchiveEntry entry : Collections.list((Enumeration<ZipArchiveEntry>) zipFile.getEntries())) {
            String name = entry.getName();
            LOGGER.info("process entry {}", name);
            InZipFile lastInZipFile = null;
            for (String split : name.split("/")) {
                if (split.length() == 0) {
                    continue;
                }
                List<InZipFile> children;
                if (lastInZipFile == null) {
                    children = inZipFiles;
                } else {
                    children = lastInZipFile.getChildren();
                }
                if (children == null) {
                    children = new ArrayList<InZipFile>();
                    lastInZipFile.setChildren(children);

                    lastInZipFile = new InZipFile(lastInZipFile, split);
                    children.add(lastInZipFile);
                    LOGGER.info("add first child {}", split);
                } else {
                    boolean found = false;
                    for (InZipFile inZipFile : children) {
                        if (inZipFile.getName().equals(split)) {
                            lastInZipFile = inZipFile;
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        lastInZipFile = new InZipFile(lastInZipFile, split);
                        LOGGER.info("add child {}", split);
                        children.add(lastInZipFile);
                    }
                }
            }
            if (!entry.isDirectory()) {
                lastInZipFile.setZipEntry(entry);
            } else {
                List<InZipFile> children = lastInZipFile.getChildren();
                if (children == null) {
                    children = new ArrayList<InZipFile>();
                    lastInZipFile.setChildren(children);
                }
            }
        }
        return inZipFiles;
    }

    public static String uri(final InZipFile currentDirectory) {
        if (currentDirectory == null) {
            return "/";
        }
        StringBuilder stringBuilder = new StringBuilder(currentDirectory.getName());
        InZipFile parent = currentDirectory.getParent();
        while (parent != null) {
            stringBuilder.insert(0, '/');
            stringBuilder.insert(0, parent.getName());
            parent = parent.getParent();
        }
        stringBuilder.insert(0, '/');
        return stringBuilder.toString();
    }

}
